package com.offcn.test;

import java.util.concurrent.CountDownLatch;

public class CASTest1 {
    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        Storage storage = new Storage();
        CountDownLatch cd = new CountDownLatch(1000);
        for (int i=0;i<1000;i++){
            new Thread(()->{
                for (int x=0;x<100;x++){
//                    storage.incr();
                    storage.incrCAS();
                }
                cd.countDown();
            }).start();
        }
        cd.await();
        long end = System.currentTimeMillis();
        System.out.println(storage.i);
        System.out.println("运行时间:"+(end-start));
    }

}

class Storage{
    int i = 0;
    public synchronized void incr(){
        i++;
    }


    public void incrCAS(){
        while (!compareAndSwap(i,i+1)){}
    }
    /**
     *  如果期望值和内存中现在的值一致,就将新值赋值给内存中的变量
     *  并且返回true,否则返回false
     * @param expectNum 期望值
     * @param newNum    新值
     * @return
     */
    public synchronized boolean compareAndSwap(int expectNum,int newNum){
        if (this.i==expectNum){
            this.i = newNum;
            return true;
        }else {
            return false;
        }
    }
}